package cn.tedu.autoshow.website.service.impl;

import cn.tedu.autoshow.commons.ex.ServiceException;
import cn.tedu.autoshow.commons.pojo.vo.PageData;
import cn.tedu.autoshow.commons.security.LoginPrincipal;
import cn.tedu.autoshow.commons.util.PageInfoToPageDataConverter;
import cn.tedu.autoshow.commons.web.ServiceCode;
import cn.tedu.autoshow.website.mapper.AutoShowMapper;
import cn.tedu.autoshow.website.mapper.TicketOrderMapper;
import cn.tedu.autoshow.website.pojo.entity.AutoShow;
import cn.tedu.autoshow.website.pojo.entity.TicketOrder;
import cn.tedu.autoshow.website.pojo.param.AutoShowAddNewParam;
import cn.tedu.autoshow.website.pojo.param.AutoShowUpdateInfoParam;
import cn.tedu.autoshow.website.pojo.vo.AutoShowListItemVO;
import cn.tedu.autoshow.website.pojo.vo.AutoShowStandardVO;
import cn.tedu.autoshow.website.service.IAutoShowService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static cn.tedu.autoshow.commons.constants.StatusConstants.*;

@Service
@Slf4j
public class AutoShowServiceImpl implements IAutoShowService {


    @Autowired
    AutoShowMapper autoShowMapper;
    @Autowired
    TicketOrderMapper cvsTicketOrderMapper;

    /*添加车展场次 */
   public void addNew(AutoShowAddNewParam autoShowAddNewParam, LoginPrincipal loginPrincipal){
       log.debug("开始处理【添加车展】的业务，参数：{}", autoShowAddNewParam);
       /*判断开的的车展时间是否与已经开启的车展时间重叠*/
       /*QueryWrapper<AutoShow> queryWrapper1 = new QueryWrapper<>();
       QueryWrapper<AutoShow> queryWrapper2 = new QueryWrapper<>();
       queryWrapper1.eq("startTime", autoShowAddNewParam.getStartTime());
       queryWrapper2.eq("endTime", autoShowAddNewParam.getEndTime());
       int countByStartTime = autoShowMapper.selectCount(queryWrapper1);
       int countByEndTime = autoShowMapper.selectCount(queryWrapper2);
       log.debug("根据车展开始结束时间匹配车展是否开放，结果：{},{}",countByStartTime,countByEndTime);
       if (countByStartTime > 0&&countByEndTime>0) {
           String message = "添加车展场次失败，该时段的车展已开放！";
           log.warn(message);
           throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
       }*/
       int n = autoShowMapper.countByStartEnd(autoShowAddNewParam.getStartTime(), autoShowAddNewParam.getEndTime());
       if (n > 0) {
           String message = "添加车展场次失败，该时段的车展已开放！";
           log.warn(message);
           throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
       }
       /*判断车展的标题是否重复*/
       int count = autoShowMapper.countByTitle(autoShowAddNewParam.getTitle());
       if(count>0){
           String message = "添加车展场次失败，车展标题已存在！";
           log.warn(message);
           throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
       }

       // 将车展数据写入到数据库中
       AutoShow autoShow   = new AutoShow();
       BeanUtils.copyProperties(autoShowAddNewParam, autoShow );
       autoShow.setUserId(loginPrincipal.getId());
       int row = autoShowMapper.insert(autoShow);
       if(row!=1){
           String message = "添加车展场次失败，服务器忙，请稍后再试！";
           log.warn(message);
           throw new ServiceException(ServiceCode.ERR_UNKNOWN,message);
       }
       log.debug("将新的车展场次写入到数据库，完成！");


   }

    /*根据id删除车展场次*/
    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据ID删除车展】的业务，参数：{}", id);
        // 检查车展是否存在，如果不存在，则抛出异常
        QueryWrapper<AutoShow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = autoShowMapper.selectCount(queryWrapper);
        log.debug("根据车展ID统计匹配的车展数量，结果：{}", countById);
        if (countById == 0) {
            String message = "删除车展失败，车展数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        /*车展已经开启不允许删除*/
        AutoShowStandardVO autoShow = autoShowMapper.getStandardById(id);
        if(autoShow.getEnable()==ENABLE){
            String message="删除车展失败，该车展已经开启,请先关闭车展";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

        // 检查是否有购票订单关联到了此车展，如果存在，则抛出异常
        QueryWrapper<TicketOrder> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("show_id", id);
        int countByAutoShowId = cvsTicketOrderMapper.selectCount(queryWrapper2);
        log.debug("根据车展ID统计匹配的购票订单数量，结果：{}", countByAutoShowId);
        if (countByAutoShowId > 0) {
            String message = "删除车展失败，仍有购票订单关联到此车展！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

        /*根据id删除车展*/
        int row = autoShowMapper.deleteById(id);
        if(row!=1){
            String message = "删除车展场次失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UNKNOWN,message);
        }

    }

    /*根据id更新车展场次*/
    @Override
    public void updateById(Long id, AutoShowUpdateInfoParam autoShowUpdateInfoParam) {
        log.debug("开始处理【修改车展详情】的业务，ID：{}, 新数据：{}", id, autoShowUpdateInfoParam);
        // 检查车展是否存在，如果不存在，则抛出异常
        AutoShowStandardVO queryResult = autoShowMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "查询车展详情失败，车展数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查车展名称是否被其它车展占用，如果被占用，则抛出异常
        QueryWrapper<AutoShow> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("title", autoShowUpdateInfoParam.getTitle())
                .ne("id", id);
        int countByName = autoShowMapper.selectCount(queryWrapper2);
        log.debug("根据车展名称统计匹配的车展数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "修改车展详情失败，车展名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        /*修改四个时间点任意一个，需要先禁用车展*/
        if(checkDateChange(queryResult,autoShowUpdateInfoParam)){
            AutoShowStandardVO autoShow = autoShowMapper.getStandardById(id);
            if(autoShow.getEnable()==ENABLE){
                String message="修改车展失败，该车展已经开启,请先关闭车展";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_DELETE, message);
            }
        }

        // 执行修改
        AutoShow autoShow = new AutoShow();
        BeanUtils.copyProperties(autoShowUpdateInfoParam, autoShow);
        autoShow.setId(id);
        int rows = autoShowMapper.updateById(autoShow);
        if (rows != 1) {
            String message = "修改车展详情失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的车展数据更新入到数据库，完成！");
    }

    //四个时间点是否修改
    private boolean checkDateChange(AutoShowStandardVO oldShow,AutoShowUpdateInfoParam newShow){
        if(!oldShow.getStartTime().isEqual(newShow.getStartTime())){
            return true;
        }
        if(!oldShow.getEndTime().isEqual(newShow.getEndTime())){
            return true;
        }
        if(!oldShow.getBuyTime().isEqual(newShow.getBuyTime())){
            return true;
        }
        if(!oldShow.getReturnTime().isEqual(newShow.getReturnTime())){
            return true;
        }
        return false;
    }

    @Override
    public void setEnable(Long id) {
        updateEnableById(id, ENABLE);
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id, ENABLE_DIS);
    }

    private void updateEnableById(Long id, Integer enable){
        String text = ENABLE_TEXT[enable];
        log.info("开始:【" + text + "管理员】");
        log.debug("传入参数,id={}, enable={} ", id, enable);

        //检查数据是否存在，如果不存在，则抛出异常
        AutoShowStandardVO queryResult = autoShowMapper.getStandardById(id);
        log.info("规则：根据管理员id检索数据库结果,queryResult={}", queryResult);
        if (queryResult == null) {
            String message = text + "车展失败，车展数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        if(queryResult.getEnable() == enable){
            String message = text + "车展失败，此车展已经处于" + text + "状态！";
            log.info("结果3:根据车展启用状态与要修改状态一致，抛出异常...");
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        AutoShow autoShow = new AutoShow();
        autoShow.setId(id);
        autoShow.setEnable(enable);
        int rows = autoShowMapper.updateById(autoShow);
        if(rows != 1){
            String message = text+"车展失败，服务器忙，请稍后再试！";
            log.info("结果1:数据返回行数不满足预估行数，预估={}, 实际={}, 抛出自定异常...", 1, rows);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.info("结果1:根据id" + text + "车展结果,rows={}", rows);
    }

    @Override
    public AutoShowStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询车展详情】的业务，参数：{}", id);
        AutoShowStandardVO queryResult = autoShowMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "查询车展详情失败，车展数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<AutoShowListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum, pageSize);
    }

    @Override
    public PageData<AutoShowListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询相册列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<AutoShowListItemVO> list = autoShowMapper.list();
        PageInfo<AutoShowListItemVO> pageInfo = new PageInfo<>(list);
        PageData<AutoShowListItemVO> pageData = PageInfoToPageDataConverter.converter(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

}
